<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/15
 * Time: 11:57
 */

namespace App\Http\Controllers\Api;


use App\Models\Member;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Cache;

class LoginController extends BaseController
{
    /**
     * 微信授权登录
     * @return array
     */
    public function wxLogin()
    {
        $app = Factory::miniProgram($this->config);
        $data = $app->auth->session($this->request->post('code'));
        //判断code是否过期
        if (isset($data['errcode'])) {
            return Response()->json(['code'=>201,'msg'=>'code已过期或不正确！']);
        }
        $weappOpenid = $data['openid'];
        $weixinSessionKey = $data['session_key'];
        $member = Member::where('openid',$weappOpenid)->first();
        if($member){ //存在更新用户数据
            $member->nickname = $this->request->post('nickname');
            $member->avatar  = $this->request->post('avatar');
            $member->session_key = $weixinSessionKey;
        }else{
            $member = new Member();
            $member->openid = $weappOpenid;
            $member->nickname = $this->request->post('nickname');
            $member->avatar  = $this->request->post('avatar');
            $member->session_key = $weixinSessionKey;
        }
        $save = $member->save();
        if(!$save){
            return Response()->json(['code'=>201,'msg'=>'登录更新用户信息失败！']);
        }
        $token = setToken($weappOpenid);
        Cache::add($token,$member->toArray(),24*60*60*15);
        return Response()->json(['code'=>200,'msg'=>'登录成功！','data'=>['token'=>$token]]);


    }

}
